<?php
namespace App\Services;

use App\PartnerGroupType;
use App\PartnerGroupTypePermission;
use App\UserGroup;
use App\Lib\Util\QueryPager;
use DB;
use App\News;

class NewsService
{
    public function getNews(Array $input, $paging = true)
    {
        $query = $this->baseQuery();

        if (!empty($input['title'])) {
            $query = $query->where('title', 'like', '%' . $input['title'] . '%');
        }

        if (!empty($input['type'])) {
            $query = $query->where('type', $input['type']);
        }

        $pager = new QueryPager($query);
        $pager->mapField('type', News::$NEWS_TYPE);

        return $paging ? $pager->doPaginate($input, 'created_at') :
            $pager->queryWithoutPaginate($input, 'created_at');
    }

    public function getNewsDetail(Array $input)
    {
        $query = News::where('id', '=', $input['id']);
        $pager = new QueryPager($query);
        $pager->mapField('type', News::$NEWS_TYPE);
        return $pager->queryWithoutPaginate($input, 'created_at')?$pager->queryWithoutPaginate($input, 'created_at')[0]:[];
    }

    private function baseQuery()
    {
        return News::select('id','title','picture','type','description','province_id','city_id','created_at');
    }

    public function saveUpdateNews($data)
    {
        DB::transaction(function () use ($data) {
            $partnerGroup = News::findOrFail($data['id']);
            $partnerGroup->update([
                'id' => $data['id'],
                'title' => $data['title'],
                'picture' => $data['picture'],
                'type' => $data['type'],
                'description' => $data['description'],
                'province_id' => $data['province_id'],
                'city_id' => $data['city_id'],
            ]);

            $partnerGroup->save();
        });
    }
}
